# app/services/wechat_service.py
import requests
import logging
from flask import current_app

logger = logging.getLogger(__name__)

class WechatService:
    @staticmethod
    def code2session(code):
        # 检查配置是否存在
        required_configs = ['WECHAT_APPID', 'WECHAT_SECRET', 'WECHAT_CODE2SESSION_URL']
        missing_configs = []
        
        # 逐个检查配置，添加更详细的日志
        for config in required_configs:
            value = current_app.config.get(config)
            if not value:
                missing_configs.append(config)
                logger.error(f"配置项 {config} 不存在或为空")
        
        if missing_configs:
            error_msg = f"缺少微信配置: {', '.join(missing_configs)}"
            logger.error(error_msg)
            return {'errcode': -2, 'errmsg': error_msg}
        
        appid = current_app.config['WECHAT_APPID']
        secret = current_app.config['WECHAT_SECRET']
        url = current_app.config['WECHAT_CODE2SESSION_URL']
        
        # 记录调试信息（部分隐藏密钥）
        masked_secret = secret[:3] + '*' * (len(secret) - 3) if secret else "未设置"
        logger.debug(f"调用微信接口: appid={appid}, secret={masked_secret}, url={url}")
        
        params = {
            'appid': appid,
            'secret': secret,
            'js_code': code,
            'grant_type': 'authorization_code'
        }
        
        try:
            response = requests.get(url, params=params, timeout=10)
            response.raise_for_status()
            res_data = response.json()
            
            # 记录完整响应
            logger.debug(f"微信接口响应: {res_data}")
            return res_data
        except Exception as e:
            logger.error(f"微信接口调用失败: {str(e)}")
            return {'errcode': -1, 'errmsg': f'接口调用异常: {str(e)}'}